package com.telnetnz.ticketdesk.service;

import java.util.Set;

import org.apache.log4j.Logger;

import com.rockbb.common.config.Config;
import com.rockbb.common.utilities.internet.Email;
import com.rockbb.common.utilities.internet.SmtpMailSender;
import com.rockbb.common.utilities.text.StringUtils;


public class SMTPService 
{
	private static Logger logger = Logger.getLogger(SMTPService.class);

	/**
	 * Send alert email
	 * 
	 * @param subject
	 * @param body
	 * @param encoding
	 * @param recipients
	 */
	public static void sendMail(String subject, String body, String encoding, Set<String> recipients) 
	{
		if((subject == null || subject.length() == 0) 
				|| (body == null || body.length() == 0)
				|| (recipients == null || recipients.size() == 0))
		{
			logger.error("Alert email exited on param error");
			return;
		}

		SmtpMailSender smtpMailSender = SmtpMailSender.getInstance();		
		smtpMailSender.initMailSession(
				Config.getValue("mail.alerts.host"), 
				Config.getValue("mail.alerts.username"), 
				Config.getValue("mail.alerts.password"), 
				true);

		try
		{
			Email email = new Email();
			email.setSubject(subject);
			email.setBody(body);
			email.setFromAddr(Config.getValue("mail.alerts.from"));
			email.setToAddr(recipients);
			email.setEncode(encoding);
			if (!Config.inDevelopment())
			{
				smtpMailSender.sendmail(email);
				logger.info("Alert email sending succeeded, email_addr:[" + StringUtils.implode(recipients, ", ")+"]");
			}
			else
				logger.info("[Dev]Alert email sending succeeded, email_addr:[" + StringUtils.implode(recipients, ", ")+"]");
		}
		catch(Exception e)
		{
			logger.error("Alert email sending failed, error:[" + e.getMessage()+"]");
		}
	}
}
